<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="接口路径" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'interfaceUrl', validatorRules.interfaceUrl]" placeholder="请输入接口路径"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'name', validatorRules.name]" placeholder="请输入名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="条件类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select @change="changeConditionCategory" v-decorator="[ 'conditionCategory', validatorRules.conditionCategory]" placeholder="请选择条件类别">
                <a-select-option v-for="(item, index) in conditionCategoryList" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="条件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select @change="changeConditions" v-decorator="[ 'conditions', validatorRules.conditions]" placeholder="请选择条件">
                <a-select-option v-for="(item, index) in conditionsList" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="条件结果" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--角色-->
              <template v-if="conditionCategory=='currentRole'">
                <a-select
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  mode="multiple"
                  style="width: 100%"
                  @change="changeRole"
                  placeholder="请选择角色"
                  v-model="selectedRole"
                >
                  <a-select-option v-for="(role, roleindex) in roleList" :key="roleindex.toString()" :value="role.id"
                  >{{ role.roleName }}
                  </a-select-option>
                </a-select>
              </template>
              <!--部门-->
              <template v-if="conditionCategory=='currentDepart'">
                <a-input-search
                  :title="conditionResultsText"
                  placeholder="请选择部门"
                  v-model="conditionResultsText"
                  read-only
                  style="width: 100%"
                  @search="onSearch('conditionResults')"
                >
                  <a-button slot="enterButton">选择部门</a-button>
                </a-input-search>
              </template>
              <!--用户-->
              <template v-if="conditionCategory=='currentUser'">
                <a-row :gutter='24'>
                  <a-col :span='3'>
                    <a-button type='primary' icon='plus' @click="openUserModal('conditionResults')" size="small">选择</a-button>
                  </a-col>
                </a-row>
                <a-row :gutter='24'>
                  <a-col :span='24'>
                    <a-textarea v-model='conditionResultsText' read-only placeholder='请选择用户'
                                :title='conditionResultsText'
                                :autosize='{ minRows: 1 }'></a-textarea>
                  </a-col>
                </a-row>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="优先级" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :min="0" :precision="0.1" v-decorator="[ 'priority', validatorRules.priority]" placeholder="请输入优先级" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="表名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-search
                v-decorator="[ 'tableName', validatorRules.tableName]"
                placeholder="请选择表名"
                read-only
                @search="openTableNameList">
                <a-button slot="enterButton">选择表名</a-button>
              </a-input-search>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="表描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'tableDescription', validatorRules.tableDescription]" read-only placeholder="请输入表描述"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="字段名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                :disabled="!tableInfo.tableName"
                v-decorator="[ 'fieldName', validatorRules.fieldName]" placeholder="请选择字段"
                @change="fieldNameChange"
                :allowClear="false"
                showSearch
                optionFilterProp="children"
                :filterOption="filterOption"
              >
                <a-select-option v-for="(item, index) in fieldNameList" :key="index" :value="item.columnName">
                  {{ item.columnName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="字段描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'fieldDescription', validatorRules.fieldDescription]" read-only placeholder="请输入字段描述"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="数据判断类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select @change="changeDataJudgeCategory" v-decorator="[ 'dataJudgeCategory', validatorRules.dataJudgeCategory]" placeholder="请选择数据判断类别">
                <a-select-option v-for="(item, index) in dataJudgeCategoryList" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="数据判断结果" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--部门-->
              <template v-if="dataJudgeCategory=='depart'">
                <a-input-search
                  :title="dataJudgeResultsText"
                  placeholder="请选择部门"
                  v-model="dataJudgeResultsText"
                  read-only
                  style="width: 100%"
                  @search="onSearch('dataJudgeResults')"
                >
                  <a-button slot="enterButton">选择部门</a-button>
                </a-input-search>
              </template>
              <!--用户-->
              <template v-if="dataJudgeCategory=='user'">
                <a-row :gutter='24'>
                  <a-col :span='3'>
                    <a-button type='primary' icon='plus' @click="openUserModal('dataJudgeResults')" size="small">选择</a-button>
                  </a-col>
                </a-row>
                <a-row :gutter='24'>
                  <a-col :span='24'>
                    <a-textarea v-model='dataJudgeResultsText' read-only placeholder='请选择用户'
                                :title='dataJudgeResultsText'
                                :autosize='{ minRows: 1 }'></a-textarea>
                  </a-col>
                </a-row>
              </template>
              <!--spl语句-->
              <template v-if="dataJudgeCategory=='sql'">
                <a-textarea v-model="dataJudgeResults" placeholder="请输入sql语句" :autosize="{minRows:3}"></a-textarea>
              </template>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--<a-input v-decorator="[ 'status', validatorRules.status]" placeholder="请输入状态 0停止 1启用"></a-input>-->
              <a-switch checkedChildren="启用" unCheckedChildren="停止" @change="onChose" v-model="statusCheck"/>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
      <depart-window ref="departWindow" @ok="departCallback"></depart-window>
      <j-select-table-name ref="tableName" @ok="tableNameCallback"></j-select-table-name>
      <act-select-user-modal ref="userModal" @ok="userCallback"></act-select-user-modal>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction ,getAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import { queryall } from '@/api/api'
  import departWindow from '../actcandidateconfig/modules/DepartWindow'
  import JSelectTableName from '../actcandidateconfig/modules/JSelectTableName'
  import ActSelectUserModal from "../actcandidateconfig/modules/ActSelectUserModal";
  export default {
    name: "DataRuleModal",
    components: {
      ActSelectUserModal,
      departWindow,
      JSelectTableName
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title:"操作",
        width: document.body.clientWidth * 0.6,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
        interfaceUrl:{rules:[{required:true,message:'请输入接口路径！'}]},
        name:{rules:[{required:true,message:'请输入名称！'}]},
        conditionCategory:{},
        conditions:{},
        conditionResults:{},
        priority:{},
        tableName:{},
        tableDescription:{},
        fieldName:{},
        fieldDescription:{},
        dataJudgeCategory:{},
        dataJudgeResults:{},
        status:{},
        },
        url: {
          add: "/datarule/dataRule/add",
          edit: "/datarule/dataRule/edit",
          fieldName:'/actcandidateconfig/actCandidateConfig/queryColumnsByTableName'
        },
        conditionCategoryList:[
          {
            text:' 当前角色',
            value:'currentRole'
          },
          {
            text:' 当前部门',
            value:'currentDepart'
          },
          {
            text:' 当前用户',
            value:'currentUser'
          }
        ],
        conditionsList:[
          {
            text:'in',
            value:'in'
          },
          {
            text:'not in',
            value:'notin'
          }
        ],
        conditionCategory:'',
        roleList:[],
        selectedRole: [],
        conditionResults:'',
        conditionResultsText:'',
        tableInfo:{},
        fieldNameList:[],
        fieldInfo:{},
        dataJudgeCategoryList:[
          {
            text:'当前用户主键',
            value:'currentUserId'
          },
          {
            text:' 部门',
            value:'depart'
          },
          {
            text:' 用户',
            value:'user'
          },
          {
            text:' sql语句',
            value:'sql'
          }
        ],
        dataJudgeCategory:'',
        dataJudgeResults:'',
        dataJudgeResultsText:'',
        currentFiled:'',
        status:1,
        statusCheck:true,
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.initialRoleList();
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          //'conditionResults',,'dataJudgeResults',,'status'
          this.form.setFieldsValue(pick(this.model,'interfaceUrl','name','conditionCategory','conditions','priority','tableName','tableDescription','fieldName','fieldDescription','dataJudgeCategory'))
        })
        if(record.id) {
          this.tableInfo.tableName = record.tableName;
          if (this.tableInfo.tableName) {
            this.getFieldNameList()
          }
          //条件类别 结果 回显
          this.conditionCategory=record.conditionCategory;
          this.conditionResults=record.conditionResults;
          this.conditionResultsText=record.conditionResultsText;
          if(this.conditionCategory==='currentRole'){
            this.selectedRole=this.conditionResults.split(',')
          }
          //数据判断类别 结果回显
          this.dataJudgeCategory=record.dataJudgeCategory;
          this.dataJudgeResults=record.dataJudgeResults;
          this.dataJudgeResultsText=record.dataJudgeResultsText;
          //状态回显
          this.status=record.status;
          this.statusCheck=record.status==1
        }
      },
      close () {
        this.roleList=[];
        this.selectedRole=[];
        this.status=1;
        this.statusCheck=true;
        this.currentFiled='';
        this.conditionCategory='';
        this.conditionResults='';
        this.conditionResultsText='';
        this.dataJudgeCategory='';
        this.dataJudgeResults='';
        this.dataJudgeResultsText='';
        this.tableInfo={};
        this.fieldInfo={};
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.status=that.status;
            formData.conditionResults=that.conditionResults;
            formData.conditionResultsText=that.conditionResultsText;
            formData.dataJudgeResults=that.dataJudgeResults;
            formData.dataJudgeResultsText=that.dataJudgeResultsText;
            // console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      handleCancel () {
        this.close()
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      //角色下拉获取
      initialRoleList() {
        queryall().then((res) => {
          if (res.success) {
            this.roleList = res.result
          } else {
            console.log(res.message)
          }
        })
      },
      // 修改角色
      changeRole(e){
        if(e.length>0){
          this.conditionResultsText='';
          this.conditionResults=e.join(',');
          //获取角色名逗号拼接给conditionResultsText
          e.forEach(item=>{
            this.conditionResultsText+=this.roleList.filter(items => items.id === item)[0].roleName+',';
          })
        }else{
          this.conditionResults='';
          this.conditionResultsText=''
        }
      },
      // 搜索用户对应的部门API
      onSearch(e) {
        this.currentFiled=e
        this.$refs.departWindow.add()
      },
      // 部门回调
      departCallback(depart){
        //条件类别-部门回调
        if(this.currentFiled==='conditionResults'){
          this.conditionResultsText='';
          this.conditionResults='';
          if(depart.length>0){
            depart.forEach((item,index)=>{
              if(index+1==depart.length){
                this.conditionResultsText+=item.title;
                this.conditionResults+=item.value
              }else{
                this.conditionResultsText+=item.title+',';
                this.conditionResults+=item.value+','
              }

            })
          }
        }else{
          //数据判断类别-部门回调
          this.dataJudgeResults='';
          this.dataJudgeResultsText='';
          if(depart.length>0){
            depart.forEach((item,index)=>{
              if(index+1==depart.length){
                this.dataJudgeResultsText+=item.title;
                this.dataJudgeResults+=item.value
              }else{
                this.dataJudgeResultsText+=item.title+',';
                this.dataJudgeResults+=item.value+','
              }
            })
          }
        }


      },
      openUserModal(e){
        this.currentFiled=e
        if(this.currentFiled==='conditionResults'){
          if (this.conditionResults) {
            var record = {
              userIds: this.conditionResults,
              userNames: this.conditionResultsText
            }
            this.$refs.userModal.open(record)
          } else {
            this.$refs.userModal.open({})
          }
        }else{
          if (this.dataJudgeResults) {
            var record = {
              userIds: this.dataJudgeResults,
              userNames: this.dataJudgeResultsText
            }
            this.$refs.userModal.open(record)
          } else {
            this.$refs.userModal.open({})
          }
        }
      },
      userCallback(users){
        if(this.currentFiled==='conditionResults'){
          //字段条件结果的用户 conditionResults
          this.conditionResultsText='';
          this.conditionResults='';
          if(users.length>0){
            users.forEach((item,index)=>{
              if(index+1==users.length){
                this.conditionResultsText+=item.realname;
                this.conditionResults+=item.id
              }else{
                this.conditionResultsText+=item.realname+',';
                this.conditionResults+=item.id+','
              }

            })
          }
        }else{
          //数据判断类别-用户 dataJudgeResults
          this.dataJudgeResults='';
          this.dataJudgeResultsText='';
          if(users.length>0){
            users.forEach((item,index)=>{
              if(index+1==users.length){
                this.dataJudgeResultsText+=item.realname;
                this.dataJudgeResults+=item.id
              }else{
                this.dataJudgeResultsText+=item.realname+',';
                this.dataJudgeResults+=item.id+','
              }

            })
          }
        }

      },
      openTableNameList(){
        this.$refs.tableName.show()
      },
      tableNameCallback(tableInfo){
        // console.log(tableInfo)
        this.tableInfo=tableInfo;
        this.form.setFieldsValue({ tableName: tableInfo.tableName,tableDescription: tableInfo.tableComment});
        this.form.setFieldsValue({ fieldName: ''});
        this.form.setFieldsValue({ fieldDescription: ''});
        this.fieldInfo={};
        this.getFieldNameList()
      },
      getFieldNameList(){
        let param={
          tableName:this.tableInfo.tableName
        };
        getAction(this.url.fieldName,param).then((res)=>{
          if(res.success){
            this.fieldNameList=res.result
          }
        })
      },
      // 字段修改
      fieldNameChange(e){
        this.fieldInfo=this.fieldNameList.filter(item => item.columnName === e)[0];
        let fieldDescription=this.fieldInfo.columnComment;
        this.form.setFieldsValue({ fieldDescription: fieldDescription})
      },
      changeConditionCategory(e){
        this.conditionCategory=e;
        this.conditionResults='';
        this.conditionResultsText='';
        this.selectedRole=[]
      },
      changeConditions(e){
        // console.log(e)
      },
      changeDataJudgeCategory(e){
        this.dataJudgeCategory=e;
        this.dataJudgeResults='';
        this.dataJudgeResultsText='';
      },
      onChose(checked) {
        if (checked) {
          this.status = 1;
          this.statusCheck = true;
        } else {
          this.status = 0;
          this.statusCheck = false;
        }
      },


    }
  }
</script>